package user_follow

import (
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/app"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/database"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/paginator"
	"gorm.io/gorm"

	"github.com/gofiber/fiber/v2"
)

func Get(id uint64) (userFollow UserFollow) {
	database.DB.Where("id", id).First(&userFollow)
	return
}

func GetFollowsCountByUserId(userId uint64) (count int64) {
	database.DB.Model(UserFollow{}).Where("user_id", userId).Where("type", FOLLOW_DRIVER).Count(&count)
	return
}

func GetByFollowIdAndUserId(followId uint64, userId uint64) (userFollow UserFollow) {
	database.DB.Where("follow_id", followId).Where("user_id", userId).First(&userFollow)
	return
}

func DeleteForever(userFollow UserFollow) bool {
	res := database.DB.Unscoped().Delete(userFollow)

	return res.RowsAffected == 1
}

func GetBy(field, value string) (userFollow UserFollow) {
	database.DB.Where("? = ?", field, value).First(&userFollow)
	return
}

func GetFollows(userId uint64, followType int) (userFollows []UserFollow) {
	database.DB.Preload("Follow", func(db *gorm.DB) *gorm.DB {
		return db.Preload("Driver")
	}).Where("user_id = ? and type = ?", userId, followType).Order("id desc").Find(&userFollows)
	return
}

func GetFollowsCount(userId uint64, followType int) (count int64) {
	database.DB.Model(UserFollow{}).Where("user_id = ? and type = ?", userId, followType).Count(&count)
	return
}

// 是否关注
func IsFollow(userId uint64, followId uint64, followType int) bool {
	var count int64
	database.DB.Model(UserFollow{}).Where("user_id = ? and follow_id = ? and type = ?", userId, followId, followType).Count(&count)
	return count > 0
}

func All() (userFollows []UserFollow) {
	database.DB.Order("id desc").Find(&userFollows)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(UserFollow{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

// Paginate 分页内容
func Paginate(c *fiber.Ctx, perPage int) (userFollows []UserFollow, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(UserFollow{}),
		&userFollows,
		app.V1URL(database.TableName(&UserFollow{})),
		perPage,
	)
	return
}
